package com.lms.busi.common.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lms.busi.common.service.ITLmsOrganizationLeaderService;
import com.lms.busi.common.service.ITLmsOrganizationService;
import com.lms.common.entity.TLmsFile;
import com.lms.common.entity.TLmsOrganization;
import com.lms.common.entity.TLmsOrganizationLeader;
import com.lms.common.file.api.client.FileClient;
import com.lms.common.pure.entity.ITreeNode;
import com.lms.common.pure.query.QueryParams;
import com.lms.common.web.controller.BaseController;
import com.lms.common.web.utils.CheckEntityResult;
import feign.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/tLmsOrganization")
@PreAuthorize("hasRole('ADMIN') or hasRole('COMPANY_ADMIN')")
@RequiredArgsConstructor
public class TLmsOrganizationController extends BaseController<ITLmsOrganizationService, TLmsOrganization> {

    private final ITLmsOrganizationLeaderService lmsOrganizationLeaderService;

    private final FileClient fileClient;

    @GetMapping("/toggleStatus/{id}")
    public void toggleStatus(@PathVariable("id") String id) {
        this.baseService.toggleStatus(id);
    }

    @GetMapping("/organizationTreeList")
    public List<ITreeNode<String>> organizationTreeList() {
        String isVirtual = request.getParameter("needVirtual");
        boolean needVirtual = "1".equals(isVirtual);
        return this.baseService.organizationaTreeList(needVirtual);
    }

    @PostMapping("/hello2")
    public void hello2(@RequestPart("file") MultipartFile uploadFile,
                       @RequestParam("businessId") String businessId,
                       @RequestParam("businessType") String businessType,
                       @RequestParam("businessColumn") String businessColumn) {
        fileClient.upload(uploadFile, businessId, businessType, businessColumn);
    }

    @GetMapping("/hello")
    public void hello(HttpServletResponse response) throws IOException {
        Response res = fileClient.download();
        Response.Body body = res.body();
        response.reset();
        InputStream inputStream = null;
        BufferedInputStream bufferedInputStream = null;
        OutputStream outputStream = null;
        try {
            String fileName = "gg.txt";
            // 设置ContentType，响应内容为二进制数据流，编码为utf-8，此处设定的编码是文件内容的编码
            response.setContentType("application/octet-stream;charset=utf-8");
            // 以（Content-Disposition: attachment; filename="filename.jpg"）格式设定默认文件名，设定utf编码，此处的编码是文件名的编码，使能正确显示中文文件名
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ";filename*=utf-8''" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            inputStream = res.body().asInputStream();
            //使用这个buffereInputStream 为了防止大文件内存溢出
            bufferedInputStream = new BufferedInputStream(inputStream);
            outputStream = response.getOutputStream();
            //每次取出5M
            byte[] buffer = new byte[1024 * 1024 * 5];
            int len;
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (Exception e) {
//            log.error("下载文件异常：{}", fileName, e);
        } finally {
            if (inputStream!=null){
                inputStream.close();
            }
            if (outputStream!=null){
                outputStream.close();
            }
            if (bufferedInputStream!=null){
                bufferedInputStream.close();
            }
        }
    }

    @Override
    @Operation(summary = "通用表格查询方法")
    @PostMapping("/query")
    public IPage<?> query(@Parameter(description = "查询参数") @RequestBody QueryParams<Map<String, Object>> queryParams) {
        return super.query(queryParams);
    }

    @Override
    @Operation(summary = "根据主键id获取相应实体或View信息")
    @GetMapping("/get/{id}")
    public Object get(@PathVariable("id") @Parameter(description = "主键id") Serializable id) {
        return super.get(id);
    }

    @Override
    @Operation(summary = "根据条件获取相应实体或View信息")
    @PostMapping("/getByFilter")
    public Object getByFilter(@Parameter(description = "查询参数") @RequestBody Map<String, Object> queryParams) {
        return super.getByFilter(queryParams);
    }

    @Override
    @Operation(summary = "通用保存方法")
    @PostMapping("/save")
    public TLmsOrganization save(@Parameter(description = "保存的实体类信息") @RequestBody Map<String, Object> entity) {
        return super.save(entity);
    }

    @Override
    @Operation(summary = "保存前的校验方法")
    @PostMapping("/beforeSaveCheck")
    public CheckEntityResult beforeSaveCheck(@Parameter(description = "需要校验的保存对象") @RequestBody TLmsOrganization entity) {
        return super.beforeSaveCheck(entity);
    }

    @Override
    @Operation(summary = "根据主键id删除单条信息")
    @DeleteMapping("/delete/{id}")
    public void delete(@Parameter(description = "主键id") @PathVariable("id") Serializable id) {
        super.delete(id);
    }

    @Override
    @Operation(summary = "根据主键id集合删除多条信息")
    @PostMapping("/deleteBatch")
    public void deleteBatch(@Parameter(description = "主键id集合") @RequestBody List<Serializable> ids) {
        super.deleteBatch(ids);
    }

    @Operation(summary = "关联组织机构领导人")
    @PostMapping("/relationLeader")
    public TLmsOrganizationLeader relationLeader(@Parameter(description = "组织机构领导人id及组织机构id") @RequestBody Map<String, Object> entity) {
        return lmsOrganizationLeaderService.saveEntity(entity);
    }
}
